package com.guaoran.micro.services.spring.cloud.eureka.client.user.service.provider.web.controller;

import com.guaoran.micro.services.spring.cloud.eureka.client.user.api.domain.User;
import com.guaoran.micro.services.spring.cloud.eureka.client.user.api.service.UserService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collection;
import java.util.Random;

/**
 * {@link UserService 用户服务} 提供方 REST API {@link RestController}
 *
 */
@RestController
public class UserServiceProviderRestApiController {

    @Autowired
    private UserService userService;

    /**
     * @param user User
     * @return 如果保存成功的话，返回{@link User},否则返回<code>null</code>
     */
    @PostMapping("/user/save")
    public User saveUser(@RequestBody User user) {
        if (userService.save(user)) {
            System.out.println("UserService 服务方：保存用户成功！" + user);
            return user;
        } else {
            return null;
        }
    }

    /**
     * 罗列所有的用户数据
     *
     * @return 所有的用户数据
     */
    @GetMapping("/user/list")
    public Collection<User> list() {
        return userService.findAll();
    }


    private final static Random random = new Random();

    /**
     * 当{@link #hystrix} 方法调用超时或失败时，
     * fallback 方法{@link #errorContent()}作为替代返回
     *
     * @return
     */
    @GetMapping("/hystrix")
    @HystrixCommand(
            fallbackMethod = "errorContent",
            commandProperties = {
                    @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",
                            value = "100")
            }

    )
    public String hystrix() throws Exception {

        // 如果随机时间 大于 100 ，那么触发容错
        int value = random.nextInt(200);

        System.out.println("hystrix() costs " + value + " ms.");
        Thread.sleep(value);
        return "Hello,World";
    }

    public String errorContent() {
        return "Fault";
    }

}
